import 'package:flutter/material.dart';
import 'package:sweet_app/http/api.dart';
import 'package:sweet_app/socket_io.dart';

class ChatTest extends StatefulWidget {
  @override
  _ChatTestState createState() => _ChatTestState();
}

class _ChatTestState extends State<ChatTest> {
  TextEditingController _controller = TextEditingController();

  List<String> _messages = [];

  SocketIOManager _manager;

  @override
  void initState() {
    super.initState();
    _manager = SocketIOManager(IP_ADDRESS, 9090, _callData, delimit: "\n");
  }

  @override
  void dispose() {
    if (_manager != null) {
      _manager.close();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("socket test")),
      body: Column(
        children: <Widget>[
          Container(
            height: 50,
            child: TextField(
              controller: _controller,
              onSubmitted: _onSubmit,
            ),
          ),
          Expanded(
            child: ListView.builder(
                itemBuilder: (context, index) =>
                    ListTile(title: Text(_messages[index])),
                itemCount: _messages.length),
          ),
        ],
      ),
    );
  }

  void _callData(String message) {
    message = "server: $message";
    setState(() {
      _messages.add(message);
    });
  }

  void _onSubmit(String value) {
    if (value.isNotEmpty) {
      String value1 = "client: " + value;
      setState(() {
        _messages.add(value1);
      });
      _manager.write(value).then((v) {
        print("$v 发送成功");
      }).catchError((error) {
        print("$value 发送失败, ${error}");
      });
      _controller.clear();
    }
  }
}
